require "#{SRC}/filter"
require "#{SRC}/book"
require "#{SRC}/translate"

class List

	attr_reader :list_store

	public

		def initialize
			@book = Book.new
			@popup = nil
			$glade = GladeXML.new("#{GLADE}/bibliomori.glade") {|handler| method(handler)}

			translate_labels

			# Populate list
			@list_store = Gtk::ListStore.new(
				Integer, # Code
				String,  # Name
				String,  # Author
				String, # Year
				String,  # Subgenre
				String,  # Borrowed
				Gdk::Pixbuf, # Cover
				Gdk::Pixbuf, # Language
				String,   # Genre
				Integer,  # Cod_Publisher
				Integer,  # cod_author
				Integer,  # cod_genre
				Integer,  # father
				Integer,  # cod_language
				String
			)
			populate_list(@list_store)

			# Populate the popup
			populate_popup

			# Create a tree view
			view = $glade["livros"]
			view.model = @list_store

			# Create a renderer
			renderer = Gtk::CellRendererText.new
			gfx_renderer = Gtk::CellRendererPixbuf.new
			
			# Add columns
			col = Gtk::TreeViewColumn.new(_("Cover"), gfx_renderer, :pixbuf => 6)
			view.append_column(col)
			col = Gtk::TreeViewColumn.new(_("Title"), renderer, :text => 1)
			col.sort_column_id = 1
			view.append_column(col)
			col = Gtk::TreeViewColumn.new(_("Author"), renderer, :text => 2)
			col.sort_column_id = 2
			view.append_column(col)
			col = Gtk::TreeViewColumn.new(_("Year"), renderer, :text => 3)
			col.sort_column_id = 3
			view.append_column(col)
			col = Gtk::TreeViewColumn.new(_("Genre"), renderer, :text => 8)
			col.sort_column_id = 4
			view.append_column(col)
			col = Gtk::TreeViewColumn.new(_("Subgenre"), renderer, :text => 4)
			col.sort_column_id = 5
			view.append_column(col)
			col = Gtk::TreeViewColumn.new(_("Language"), gfx_renderer, :pixbuf => 7)
			view.append_column(col)
			col = Gtk::TreeViewColumn.new("", renderer, :text => 14)
			view.append_column(col)
			# col = Gtk::TreeViewColumn.new(_("Borrowed to"), renderer, :text => 5)
			# view.append_column(col)
			
			@list_store.set_sort_column_id(1, Gtk::SORT_ASCENDING)

		end

		def event(w, e)
			p e
		end

		def populate_list(store)
			store.clear
			begin
				$db.execute("SELECT book.cod_book
                            	 , name 
                        	     , author
                    	         , year
                	             , genre
            	                 , borrowed_to
							     , flag
							     , genre.father
							     , cod_publisher
						    	 , book.cod_author
							     , book.cod_genre
							     , genre.father
								 , book.cod_language
						      FROM book, author, genre, language
						     WHERE book.cod_author = author.cod_author
						       AND book.cod_genre = genre.cod_genre
	                           AND book.cod_language = language.cod_language") do |r|
					iter = store.append
					iter[0] = r[0].to_i
					iter[1] = r[1]
					iter[2] = r[2]
					if r[3].to_i == 0
						iter[3] = ''
					else
						iter[3] = r[3]
					end
					iter[4] = r[4] if r[7] != nil and r[7] != ""
					iter[5] = r[5]
					if File.readable?("#{BOOKIMGS}/#{r[0]}s.jpg")
						iter[6] = Gdk::Pixbuf.new("#{BOOKIMGS}/#{r[0]}s.jpg")
					else
						iter[6] = Gdk::Pixbuf.new("#{BOOKIMGS}/0s.jpg")
					end
					if File.readable?("#{IMG}/#{r[6]}.gif")
						iter[7] = Gdk::Pixbuf.new("#{IMG}/#{r[6]}.gif")
					else
						iter[7] = nil
					end
					if r[7] != nil and r[7] != ""
						iter[8] = $db.get_first_value("SELECT genre FROM genre WHERE cod_genre = #{r[7]}")
					elsif r[10] != nil
						iter[8] = $db.get_first_value("SELECT genre FROM genre WHERE cod_genre = #{r[10]}")
					end
					iter[9] = r[8].to_i
					iter[10] = r[9].to_i
					iter[11] = r[10].to_i
					iter[12] = r[11].to_i
					iter[13] = r[12].to_i
					iter[14] = ""
				end	
			rescue SQLite3::SQLException => e
				Error.db_error(e)
			end
		end

		# Clear the unused items from the database, and performs a VACUUM
		def cleanup_database
			begin
				$db.execute("DELETE FROM author WHERE cod_author NOT IN (SELECT cod_author FROM book) AND cod_author != 0")
				$db.execute("DELETE FROM publisher WHERE cod_publisher NOT IN (SELECT cod_publisher FROM book) AND cod_publisher != 0")
				$db.execute("DELETE FROM language WHERE cod_language NOT IN (SELECT cod_language FROM book) AND cod_language != 0")
				$db.execute("DELETE FROM genre WHERE cod_genre NOT IN (SELECT cod_genre FROM book) AND cod_genre != 0 AND father != '' AND father IS NOT NULL")
				$db.execute("DELETE FROM genre WHERE cod_genre NOT IN (SELECT cod_genre FROM book) AND cod_genre != 0 AND (father == '' OR father IS NULL) AND cod_genre NOT IN (SELECT father FROM genre, book WHERE book.cod_genre = genre.cod_genre)")
			rescue SQLite3::SQLException => e
				puts "WARNING: error cleaning up database:\n#{e.message}"
			end
		end

	private
		
		def double_click(view, path, column)
			if iter = view.model.get_iter(path)
				@book.show(iter[0])
			end
		end

		def on_add_book
			@book.show
		end

		def on_close
			Gtk.main_quit
		end

	#
	# exception
	#

		def error_ok
			$glade["exception"].hide_on_delete
		end

end
